package com.cms.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import com.cms.entity.ArcType;
import com.cms.entity.Article;
import com.cms.entity.Link;
import com.cms.service.ArcTypeService;
import com.cms.service.ArticleService;
import com.cms.service.LinkService;
/**
 * 初始化组件
 * @author user
 *
 */
@Component("initComponet")
public class InitComponet implements ServletContextListener{	 
	
	/**
	 * 刷新application缓存方法
	 * @param application
	 * 　在 Servlet API 中有一个 ServletContextListener 接口，它能够监听 ServletContext 对象的生命周期
	 * 
	 */
	public void refreshSystem(ServletContext application){
		//这里拿到spring核心容器
		ApplicationContext act = ContextLoader.getCurrentWebApplicationContext();
		
		//掉业务逻辑层方法拿到数据
		LinkService linkService=(LinkService) act.getBean("linkService");
		List<Link> linkList=linkService.list(null);
		
		ArcTypeService arcTypeService=(ArcTypeService) act.getBean("arcTypeService");
		List<ArcType> arcTypeList=arcTypeService.list(null);
		
		ArticleService articleService=(ArticleService) act.getBean("articleService");
		List<Article> newestArticleList=articleService.getNewest(); // 获取最新8条
		List<Article> recommendArticleList=articleService.getRecommend(); 
		List<Article> slideArticleList=articleService.getSlide();
		
		
		List allIndexArticleList=new ArrayList(); // 所有栏目的最新8条文章，共48条文章
		
		if(arcTypeList!=null && arcTypeList.size()!=0){//
			
			for(int i=0;i<arcTypeList.size();i++){
				
				List<Article> subArticleList=articleService.getIndex(arcTypeList.get(i).getId());
				
				allIndexArticleList.add(subArticleList);
			}
		}

		
		//封装数据
		application.setAttribute("allIndexArticleList", allIndexArticleList);
		application.setAttribute("slideArticleList", slideArticleList);
		application.setAttribute("recommendArticleList", recommendArticleList);
		application.setAttribute("arcTypeList", arcTypeList);		
		application.setAttribute("linkList", linkList);
		application.setAttribute("newestArticleList", newestArticleList);
	}
	/**
	    * 当Servlet 容器启动Web 应用时调用该方法。在调用完该方法之后，容器再对Filter 初始化，
	    * 并且对那些在Web 应用启动时就需要被初始化的Servlet 进行初始化。
	    */
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		ServletContext application=sce.getServletContext();			
		refreshSystem(application);
	}
	/**
	    * 当Servlet 容器终止Web 应用时调用该方法。在调用该方法之前，容器会先销毁所有的Servlet 和Filter 过滤器。
	  */
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}
}

